<template>
  <div class="app-container" v-loading="loading" style="overflow-x: hidden">
    <el-form :model="form" ref="formRef" :inline="true" :rules="rules" label-width="130px">
      <el-form-item label="工厂" prop="factory">
        <el-select
          v-model="form.factory"
          placeholder="请选择"
          style="width: 240px"
          clearable
          filterable
          @change="handleSearchListChange('factory')"
        >
          <el-option
            v-for="(item, index) in factoryOptions"
            :key="index"
            :label="item.deptName"
            :value="item.deptCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工段" prop="workshopCode">
        <el-select
          v-model="form.workshopCode"
          placeholder="请选择"
          clearable
          filterable
          style="width: 240px"
          @change="handleSearchListChange('workSection')"
        >
          <el-option
            v-for="(item, index) in workshopOptions"
            :key="index"
            :label="item.deptName"
            :value="item.deptCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产线" prop="productLine">
        <el-select
          v-model="form.productLine"
          placeholder="请选择"
          clearable
          filterable
          style="width: 240px"
          @change="handleSearchListChange('productLine')"
        >
          <el-option
            v-for="(item, index) in lineOptions"
            :key="index"
            :label="item.deptName"
            :value="item.deptCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工艺段" prop="sectionCode">
        <el-select
          v-model="form.sectionCode"
          placeholder="请选择"
          multiple
          collapse-tags
          clearable
          style="width: 240px"
          @blur="handleSearchSectionCodeListBlur('sectionCode')"
        >
          <el-option
            v-for="(item, index) in processOptions"
            :key="index"
            :label="item.deptName"
            :value="item.deptCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="生产日期" prop="prodDate">
        <el-date-picker
          v-model="form.prodDate"
          type="date"
          placeholder="请选择生产日期"
          value-format="YYYY-MM-DD"
          style="width: 240px"
          @change="handleChangeProdDate()"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="班次" prop="scheduleName">
        <el-select
          v-model="form.scheduleName"
          placeholder="请选择"
          style="width: 240px"
          clearable
          filterable
          @change="handleClassesCode"
        >
          <el-option
            v-for="(item, index) in shiftGroupsList"
            :key="index"
            :label="item.scheduleName"
            :value="item.scheduleName"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="开始生产时间" prop="startProdTime">
        <el-time-picker
          v-model="form.startProdTime"
          clearable
          value-format="HH:mm:ss"
          placeholder="请选择开始生产时间"
          style="width: 240px"
        ></el-time-picker>
      </el-form-item>
      <el-form-item label="生产订单" prop="workOrderList" style="width: 100%">
        <el-button
          type="primary"
          @click="handleOrderList"
          :disabled="!form.factory || !form.workshopCode || !form.productLine || !form.sectionCode"
        >
          选择订单
        </el-button>
        <el-table :data="form.workOrderList" border style="width: 100%; margin-top: 10px">
          <el-table-column label="订单编号" prop="orderCode" width="140" />
          <el-table-column label="产品编号" prop="prodCode" />
          <el-table-column label="产品名称" prop="prodName" />
          <el-table-column label="计划产量" prop="planNumber" />
          <el-table-column label="已完工产量" prop="actualNumber" />
          <el-table-column label="完成率" prop="finishRate">
            <template #default="scope">
              <span :class="Number(scope.row.finishRate.replace('%', '')) > 100 ? 'green' : 'red'">
                {{ scope.row.finishRate }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="单位" prop="unit" />
          <el-table-column label="计划开始时间" prop="planStartTime">
            <template #default="scope">
              <span>{{ scope.row.planStartTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="计划结束时间" prop="planEndTime">
            <template #default="scope">
              <span>{{ scope.row.planEndTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="工艺段" prop="sectionName" />
          <el-table-column label="来源" prop="source">
            <template #default="scope">
              <dict-tag :options="order_source" :value="scope.row.source" />
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="status">
            <template #default="scope">
              <dict-tag :options="work_order_status" :value="scope.row.status" />
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <div class="previousClasses">
      <div>上一班信息</div>
      <previousClassTable
        ref="previousClassTableRef"
        :datas="form"
        @handleClickPrevious="handleClickPrevious"
      ></previousClassTable>
    </div>
    <div class="previousClasses" style="margin-top: 30px">
      <div>
        <span>本班人员安排</span>
      </div>
      <onDutyPersonnel
        ref="onDutyPersonnelRef"
        v-model="prodChangeShiftsMemberList"
        v-if="prodChangeShiftsMemberList && prodChangeShiftsMemberList.length > 0"
        :defaultWorkGroup="form.defaultWorkGroup"
        :parentType="'add'"
        :isShowProdHours="'no'"
      ></onDutyPersonnel>
    </div>

    <workOrderList
      @changeWorkOrderList="getWorkOrderList"
      :title="'选择生产订单'"
      :openWorkOrder="openWorkOrder"
      :sectionList="sectionInfoList"
      :sectionCodeList="form.sectionCode"
      :factory="form.factory"
      :workshopCode="form.workshopCode"
      :lineCode="form.productLine"
      :hasSelectedWorkOrderList="hasSelectedWorkOrderList"
    ></workOrderList>
  </div>
</template>

<script setup name="changeShifts">
import { toRefs } from "vue";
import { queryPreviousClassInfo, addCarryOn, editCarryOn } from "@/api/productionMgt/changeShifts";
import { getScheduleNames4ChangeShifts } from "@/api/base/plan/shiftMgt/shiftCalendar";
import { listShiftGroup } from "@/api/base/plan/shiftMgt/shiftGroup";
import {
  // getFactoryTree,
  depeIdSelectList,
} from "@/api/system/dept";
import { planGroupDetail } from "@/api/base/plan/shiftMgt/shiftGroup";
import workOrderList from "./workOrderList";
import DetailData from "./data";
import onDutyPersonnel from "./components/onDutyPersonnel";
import previousClassTable from "./components/previousClassTable";

import { ref, reactive, getCurrentInstance, onMounted } from "vue";

const { proxy } = getCurrentInstance();
const workGroupOptions = ref([]);
const { work_order_status } = proxy.useDict("work_order_status");
const { order_source } = proxy.useDict("order_source");
const loading = ref(false);
const openWorkOrder = ref(false);
const shiftGroupsList = ref([]);
const sectionInfoList = ref([]);
const prodChangeShiftsMemberList = ref([]);
const hasSelectedWorkOrderList = ref([]);
var factoryOptions = ref([]);
var workshopOptions = ref([]);
var lineOptions = ref([]);
var processOptions = ref([]);
const orderSectionCodeList = ref([]);
const emit = defineEmits(["close", "setTitle", "setActions", "setIsActionTop"]);
const actions = ref([
  {
    text: "取 消",
    theme: "",
    handle: () => {
      cancel();
    },
  },
  {
    text: "确 定",
    theme: "primary",
    handle: () => {
      submitForm();
    },
    loading: false,
  },
]);

const data = reactive({
  form: {},
  rules: {
    factory: [{ required: true, message: "工厂不能为空", trigger: "change" }],
    workshopCode: [{ required: true, message: "工段不能为空", trigger: "change" }],
    productLine: [{ required: true, message: "产线不能为空", trigger: "change" }],
    sectionCode: [{ required: true, message: "工艺段不能为空", trigger: "blur" }],
    prodDate: [{ required: true, message: "生产日期不能为空", trigger: "change" }],
    scheduleName: [{ required: true, message: "班次不能为空", trigger: "change" }],
    startProdTime: [{ required: true, message: "开始生产时间不能为空", trigger: "change" }],
    workOrderList: [{ required: true, message: "选择订单不能为空", trigger: "change" }],
  },
});

const { form, rules } = toRefs(data);

// 获取工厂列表
function getFactorys() {
  // getFactoryTree(query).then((res) => {
  //   factoryOptions.value = res.data;
  // });
  depeIdSelectList({
    deptType: "factory",
    deptCode: "",
    permissionType: "permission",
  }).then((res) => {
    factoryOptions.value = res.data;
  });
}

// 选择工厂、工段、产线后
function handleSearchListChange(type) {
  if (type == "factory") {
    workshopOptions.value = [];
    lineOptions.value = [];
    processOptions.value = [];
    form.value.workshopCode = "";
    form.value.productLine = "";
    form.value.sectionCode = "";
    resetDatas();
    if (form.value.factory) {
      depeIdSelectList({
        deptType: "station",
        deptCode: form.value.factory,
        permissionType: "permission",
      }).then((res) => {
        workshopOptions.value = res.data;
        lineOptions.value = [];
        processOptions.value = [];
        form.value.workshopCode = "";
        form.value.productLine = "";
        form.value.sectionCode = "";
      });
    }
  }
  if (type == "workSection") {
    lineOptions.value = [];
    processOptions.value = [];
    form.value.productLine = "";
    form.value.sectionCode = "";
    resetDatas();
    if (form.value.workshopCode) {
      depeIdSelectList({
        deptType: "line",
        deptCode: form.value.workshopCode,
        permissionType: "permission",
      }).then((res) => {
        lineOptions.value = res.data;
        processOptions.value = [];
        form.value.productLine = "";
        form.value.sectionCode = "";
      });
    }
  }
  if (type == "productLine") {
    processOptions.value = [];
    form.value.sectionCode = "";
    resetDatas();
    if (form.value.productLine) {
      depeIdSelectList({
        deptType: "craft",
        deptCode: form.value.productLine,
        permissionType: "permission",
      }).then((res) => {
        processOptions.value = res.data;
        form.value.sectionCode = "";
      });
    }
  }
}

// 工艺段列表选择后
function handleSearchSectionCodeListBlur() {
  if (form.value.sectionCode && form.value.sectionCode.length > 0) {
    // 更新、获取班次列表
    handleUpdateShiftList();
  } else {
    // 清空
    resetDatas();
  }
}

// 班次、班次列表、开始生产时间、上一班信息、本班人员安排均置空
function resetDatas() {
  shiftGroupsList.value = [];
  form.value.scheduleName = "";
  form.value.startProdTime = "";
  form.value.previousClassInfo = [];
  form.value.workOrderList = [];
  hasSelectedWorkOrderList.value = [];
  prodChangeShiftsMemberList.value = [];
  form.value.defaultWorkGroup = "";
}

// 生产日期选择后
function handleChangeProdDate() {
  if (form.value.prodDate) {
    // 更新、获取班次列表
    handleUpdateShiftList();
  } else {
    // 班次、班次列表、开始生产时间均置空
    shiftGroupsList.value = [];
    form.value.scheduleName = "";
    form.value.startProdTime = "";
  }
}

// 生产日期、工艺段选择后查询班次列表
function handleUpdateShiftList() {
  if (form.value.sectionCode && form.value.prodDate && form.value.factory) {
    getScheduleNames4ChangeShiftsFun();
  }
}

// 获取默认班组
function getScheduleNames4ChangeShiftsFun() {
  const sectionCode = form.value.sectionCode;
  let resArray = [];
  sectionCode.forEach((item) => {
    resArray.push(getClassesList(item));
  });
  // 当所有请求都成功完成时，responses 是一个包含所有响应的数组
  Promise.all(resArray)
    .then((responses) => {
      // 这里是对返回的班次数组进行二次组装
      // 因为会存在用户选择多条工艺段时，班次列表会存在重复，只有workGroup不一样，所以需要对数据进行二次组装
      let qrList = [];
      responses.forEach((ele, index) => {
        if (index == 0) {
          qrList.push(...ele.data);
        } else {
          let _eles = ele.data;
          for (let i in _eles) {
            for (let j in qrList) {
              if (_eles[i].scheduleName == qrList[j].scheduleName) {
                qrList[j].workGroup = qrList[j].workGroup + "," + _eles[i].workGroup;
                qrList[j].workGroupName = qrList[j].workGroupName + "," + _eles[i].workGroupName;
              }
            }
          }
        }
      });
      console.log(qrList, "=======qrList");
      shiftGroupsList.value = qrList;
      // 根据后端返回接口字段def判断默认回显值-班次、开始生产时间
      form.value.scheduleName =
        qrList.find((item) => {
          return item.def;
        })?.scheduleName || "";
      form.value.classesCode =
        qrList.find((item) => {
          return item.def;
        })?.classesCode || "";
      form.value.startProdTime =
        qrList.find((item) => {
          return item.def;
        })?.startTime || "";
      // 根据当前默认选择回填的班次---获取本班人员安排的班组列表的默认值
      form.value.defaultWorkGroup =
        qrList.find((item) => {
          return item.def;
        })?.workGroup || "";
    })
    .catch(() => {
      // 如果任何一个请求失败，将会进入这个 catch 块
      proxy.$modal.msgError("当前工艺段无排班计划，请设置后再接班");
      // 清空
      resetDatas();
      return;
    });
}

async function getClassesList(sectionCode) {
  // 根据所选工艺段、所选生产日期、工厂id后查询获取获取-班次列表
  const _prodDate = form.value.prodDate;
  const yearStr = _prodDate.substring(0, 4);
  const monthStr = _prodDate.substring(5, 7);
  const dayNo = _prodDate.substring(8);
  const deptId =
    factoryOptions.value.find((item) => {
      return item.deptCode == form.value.factory;
    })?.deptId || "";
  return await getScheduleNames4ChangeShifts({
    sectionCodeList: [sectionCode],
    yearStr,
    monthStr,
    dayNo,
    deptId,
  });
}

// 班次列表选择后
function handleClassesCode(val) {
  if (val) {
    shiftGroupsList.value.forEach((el) => {
      if (el.scheduleName == val) {
        form.value.startProdTime = el.startTime || "";
        form.value.classesCode = el.classesCode;
        // 根据当前默认选择回填的班次---获取本班人员安排的班组列表的默认值
        form.value.defaultWorkGroup = el.workGroup;
        // form.value.defaultWorkGroup =
        //   res.data.find((item) => {
        //     return item.def;
        //   })?.workGroup || "";
      }
    });
  } else {
    form.value.startProdTime = "";
    form.value.classesCode = "";
  }
}

// 点击选择订单按钮后
function handleOrderList() {
  sectionInfoList.value = [];
  // 获取当前选择的工艺段值信息，选择订单弹出框时需要默认回填工艺段名称查询列表
  if (form.value.sectionCode.length && processOptions.value.length) {
    processOptions.value.forEach((item) => {
      if (form.value.sectionCode.includes(item.deptCode)) {
        sectionInfoList.value.push(item);
      }
    });
    openWorkOrder.value = true;
  } else {
    proxy.$modal.msgError("请先选择工艺段！");
  }
}

// 选择完订单后
function getWorkOrderList(val) {
  openWorkOrder.value = false;
  if (val.length) {
    form.value.workOrderList = val;
    hasSelectedWorkOrderList.value = JSON.parse(JSON.stringify(form.value.workOrderList));
  }
  const sectionCode = form.value.workOrderList.map((el) => el.sectionCode);
  orderSectionCodeList.value = [...new Set(sectionCode)].join(",");
  if (sectionCode && sectionCode.length > 0) {
    // 上一班信息
    getPreviousClassInfo();
    // 本班人员安排
    getPlanGroupDetail();
    // 班组下拉列表
    getWorkGroupData();
  } else {
    // 上一班信息列表为空
    form.value.previousClassInfo = [];
    // 本班人员安排列表为空
    prodChangeShiftsMemberList.value = [];
    // 班组下拉列表为空
    workGroupOptions.value = [];
  }
}

// 上一班信息
function getPreviousClassInfo() {
  queryPreviousClassInfo({
    sectionCodeList: orderSectionCodeList.value.split(","),
  }).then((res) => {
    form.value.previousClassInfo = res.data;
  });
}
// 本班人员安排
function getPlanGroupDetail() {
  planGroupDetail({ section: orderSectionCodeList.value }).then((res) => {
    prodChangeShiftsMemberList.value = res.data;
    // getDefaultWorkGroupData();
    // prodChangeShiftsMemberList.value.forEach(item=>{
    //   if(item.planGroupList.length){
    //     item.planGroupList.forEach(info=>{
    //       if(info.planGroupMemberList.length){
    //         info.planGroupMemberList.forEach(ele=>{
    //           console.log();
    //           ele.children = ele.userList
    //         })
    //       }
    //     })
    //   }
    // })
  });
}

// 班组下拉列表
function getWorkGroupData() {
  listShiftGroup({ sectionCode: orderSectionCodeList.value }).then((res) => {
    workGroupOptions.value = res.rows;
  });
}

function cancel() {
  emit("close");
}

function submitForm() {
  console.log(form.value, "===form.value");
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      // 验证本班人员安排
      proxy.$refs["onDutyPersonnelRef"].$refs["formRefDuty"].validate((valid) => {
        if (valid) {
          submitData();
        }
      });
    }
  });
}

function submitData() {
  let _prodChangeShiftsMemberList = proxy.$refs?.onDutyPersonnelRef?.form?.tableData || [];
  for (let i in _prodChangeShiftsMemberList) {
    let el = _prodChangeShiftsMemberList[i];
    for (let j in el.planGroupMemberList) {
      if (!el.planGroupMemberList[j].workStationStaffName) {
        proxy.$modal.msgError(`第${Number(i) + 1}组第${Number(j) + 1}行岗位人员没有填写！`);
        return;
      }
    }
  }

  loading.value = true;
  let newList = {};
  newList.factory = form.value.factory;
  newList.factoryName =
    factoryOptions.value.find((item) => {
      return item.deptCode == form.value.factory;
    })?.deptName || "";
  newList.workshopCode = form.value.workshopCode;
  newList.workshopName =
    workshopOptions.value.find((item) => {
      return item.deptCode == form.value.workshopCode;
    })?.deptName || "";
  newList.productLine = form.value.productLine;
  newList.productLineName =
    lineOptions.value.find((item) => {
      return item.deptCode == form.value.productLine;
    })?.deptName || "";
  newList.sectionCode = form.value.sectionCode.toString();
  newList.sectionName = processOptions.value
    .map((item) => {
      if (form.value.sectionCode.includes(item.deptCode)) {
        return item.deptName;
      }
    })
    .toString();
  newList.prodDate = form.value.prodDate;
  newList.scheduleName = form.value.scheduleName;
  newList.classesCode = form.value.classesCode;
  newList.startProdTime = form.value.startProdTime;
  newList.workGroup = form.value.workGroup;
  newList.workOrderCodeList = form.value.workOrderList.map((item) => {
    return item.orderCode;
  });
  newList.prodChangeShiftsMemberList = _prodChangeShiftsMemberList.map((item) => {
    let _arr = item.planGroupMemberList.map((items) => {
      return {
        ...items,
        sectionCode: item.sectionCode.toString(),
        sectionName: item.sectionName,
      };
    });
    return {
      ...item,
      sectionCode: item.sectionCode.toString(),
      prodMemberDtoList: _arr,
      workGroupName:
        item.planGroupList.find((its) => {
          return its.workGroup == item.workGroupCode;
        })?.workGroupName || "",
    };
  });
  if (form.value.id) {
    newList.id = form.value.id;
    editCarryOn(newList)
      .then(() => {
        proxy.$modal.msgSuccess("编辑成功");
        cancel();
      })
      .catch(() => {
        loading.value = false;
      });
  } else {
    addCarryOn(newList)
      .then(() => {
        proxy.$modal.msgSuccess("提交成功");
        cancel();
      })
      .catch(() => {
        loading.value = false;
      });
  }
}

function handleClickPrevious(row) {
  proxy.subPage(DetailData, { title: "交班详情", data: row });
}
getFactorys();
onMounted(async () => {
  // 获取默认生产日期
  const today = new Date();
  const year = today.getFullYear();
  const month = today.getMonth() + 1; // JavaScript中月份从0开始
  const day = today.getDate();
  // 组合成YYYY-MM-DD格式
  const isoDate = `${year}-${month < 10 ? "0" + month : month}-${day < 10 ? "0" + day : day}`;
  form.value.prodDate = isoDate;

  actions.value = [
    {
      text: "取 消",
      theme: "",
      handle: () => {
        cancel();
      },
    },
    {
      text: "确 定",
      theme: "primary",
      handle: () => {
        submitForm();
      },
      loading: false,
    },
  ];
  emit("setActions", actions.value);
});
</script>
<style lang="scss" scoped>
.green {
  color: green;
}

.red {
  color: red;
}
</style>
